<template>
	<div class="table-main">
		<div class="titles">
			<p>策略管理</p>
			<el-button
				size="small"
				v-if="authorize == 1"
				@click="onTimeAdd"
				type="primary"
				>增加</el-button
			>
		</div>
		<div class="table-container">
			<div class="search-container">
				<el-form :inline="true" size="small">
					<el-form-item label="储能单元-季节：">
						<el-select
							v-model="page.controlManageIndexId"
							@focus="onFocus"
							@change="onChange"
							clearable
						>
							<el-option
								v-for="item in bmsSeasonList"
								:key="item.id"
								:label="item.showName"
								:value="item.id"
							>
							</el-option>
						</el-select>
					</el-form-item>
				</el-form>
			</div>
			<el-table
				:data="tacticData"
				v-loading="loading"
				style="width: 100%"
				height="calc(100% - 76px)"
				@cell-mouse-enter="handleCellEnter"
				@cell-mouse-leave="handleCellLeave"
				@cell-click="handleCellClick"
				ref="ElTableRef"
			>
				<el-table-column label="开始时间" prop="beginTime">
					<template slot-scope="scope">
						<div class="editable-cell__val">{{ scope.row.beginTime }}</div>
						<el-time-picker
							v-model="scope.row.beginTime"
							class="editable-cell__input"
							format="HH:mm"
							value-format="HH:mm"
						/>
					</template>
				</el-table-column>
				<el-table-column label="目标有功功率（MW）" prop="p" width="160px">
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.p"
						></el-input>
						<div class="editable-cell__val">{{ scope.row.p }}</div>
					</template>
				</el-table-column>
				<el-table-column label="控制组" prop="groupCtrl" width="120px">
					<template slot-scope="scope">
						<el-select
							class="editable-cell__input"
							v-model="scope.row.groupCtrl"
						>
							<el-option
								v-for="item in bmsUnitList"
								:key="item.ctrlGroupId"
								:label="item.name"
								:value="item.ctrlGroupId"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ groupCtrlFormat(scope.row.groupCtrl) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="充放指令" prop="directionCmd" width="110px">
					<template slot-scope="scope">
						<el-select
							class="editable-cell__input"
							v-model="scope.row.directionCmd"
						>
							<el-option
								v-for="item in chargeTypeDict"
								:key="item.dictValue"
								:label="item.dictLabel"
								:value="item.dictValue"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ chargeTypeFormat(scope.row.directionCmd) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="负荷跟随" prop="followLoad" width="110px">
					<template slot-scope="scope">
						<el-select
							class="editable-cell__input"
							v-model="scope.row.followLoad"
						>
							<el-option
								v-for="item in trueFalseDict"
								:key="item.dictValue"
								:label="item.dictLabel"
								:value="item.dictValue"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ trueFalseFormat(scope.row.followLoad) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column
					label="防止逆流"
					prop="disablePowReverse"
					width="110px"
				>
					<template slot-scope="scope">
						<el-select
							class="editable-cell__input"
							v-model="scope.row.disablePowReverse"
						>
							<el-option
								v-for="item in trueFalseDict"
								:key="item.dictValue"
								:label="item.dictLabel"
								:value="item.dictValue"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ trueFalseFormat(scope.row.disablePowReverse) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="SOC下限" prop="socBottom" width="120px">
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							@change="number100"
							type="number"
							min="0"
							max="100"
							v-model="scope.row.socBottom"
						></el-input>
						<div class="editable-cell__val">
							{{ scope.row.socBottom }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="SOC上限" prop="socTop" width="120px">
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.socTop"
							@change="number100"
							type="number"
							min="0"
							max="100"
						></el-input>
						<div class="editable-cell__val">
							{{ scope.row.socTop }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="COS下限" prop="cosBottom" width="120px">
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.cosBottom"
							@change="number1"
							type="number"
							min="0"
							max="1"
						></el-input>
						<div class="editable-cell__val">
							{{ scope.row.cosBottom }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="COS上限" prop="cosTop" width="120px">
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.cosTop"
							@change="number1"
							type="number"
							min="0"
							max="1"
						></el-input>
						<div class="editable-cell__val">
							{{ scope.row.cosTop }}
						</div>
					</template>
				</el-table-column>
				<el-table-column
					label="有功负荷补偿度"
					prop="ratioPCompensate"
					width="130px"
				>
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.ratioPCompensate"
							@change="number1"
							type="number"
							min="0"
							max="1"
						></el-input>
						<div class="editable-cell__val">
							{{ scope.row.ratioPCompensate }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="有功需量" prop="powerNeed">
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.powerNeed"
						></el-input>
						<div class="editable-cell__val">
							{{ scope.row.powerNeed }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="恒定无功出力" prop="constantQ" width="120px">
					<template slot-scope="scope">
						<el-select
							class="editable-cell__input"
							v-model="scope.row.constantQ"
						>
							<el-option
								v-for="item in trueFalseDict"
								:key="item.dictValue"
								:label="item.dictLabel"
								:value="item.dictValue"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ trueFalseFormat(scope.row.constantQ) }}
						</div>
					</template>
				</el-table-column>
				<!-- <el-table-column label="开始日期" prop="beginDay" width="160px">
					<template slot-scope="scope">
						<div class="editable-cell__val">{{ scope.row.beginDay }}</div>
						<el-date-picker
							v-model="scope.row.beginDay"
							class="editable-cell__input"
							type="date"
							format="MM 月 dd 日"
							value-format="MM 月 dd 日"
							placeholder="选择日期"
							style="width: 100%"
						/>
					</template>
				</el-table-column>
				<el-table-column label="终止日期" prop="endDay" width="160px">
					<template slot-scope="scope">
						<div class="editable-cell__val">{{ scope.row.endDay }}</div>
						<el-date-picker
							v-model="scope.row.endDay"
							class="editable-cell__input"
							type="date"
							format="MM 月 dd 日"
							value-format="MM 月 dd 日"
							placeholder="选择日期"
							style="width: 100%"
						/>
					</template>
				</el-table-column> -->
				<el-table-column
					label="充电时抑制需量"
					prop="limitMaxPowCh"
					width="120px"
				>
					<template slot-scope="scope">
						<el-select
							class="editable-cell__input"
							v-model="scope.row.limitMaxPowCh"
						>
							<el-option
								v-for="item in trueFalseDict"
								:key="item.dictValue"
								:label="item.dictLabel"
								:value="item.dictValue"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ trueFalseFormat(scope.row.limitMaxPowCh) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="自动调节无功" prop="adjustCosOrQ" width="120px">
					<template slot-scope="scope">
						<el-select
							class="editable-cell__input"
							v-model="scope.row.adjustCosOrQ"
						>
							<el-option
								v-for="item in trueFalseDict"
								:key="item.dictValue"
								:label="item.dictLabel"
								:value="item.dictValue"
							>
							</el-option>
						</el-select>
						<div class="editable-cell__val">
							{{ trueFalseFormat(scope.row.adjustCosOrQ) }}
						</div>
					</template>
				</el-table-column>
				<el-table-column
					label="无功补偿度"
					prop="ratioQCompensate"
					width="120px"
				>
					<template slot-scope="scope">
						<el-input
							class="editable-cell__input"
							v-model="scope.row.ratioQCompensate"
							@change="number1"
							type="number"
							min="0"
							max="1"
						></el-input>
						<div class="editable-cell__val">
							{{ scope.row.ratioQCompensate }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="160px" v-if="authorize">
					<template slot-scope="scope">
						<!-- <el-button
							size="mini"
							type="normass"
							@click="handleSeasonEdit(scope.row)"
							>编辑</el-button
						> -->
						<el-button
							@click="save(scope.row)"
							v-show="scope.row.isEdit"
							type="primary"
							size="mini"
							:class="{ 'save-btn': scope.row.isEdit }"
							>保存</el-button
						>
						<el-button
							size="mini"
							type="danger"
							@click="handleSeasonDelete(scope.row)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<div class="table-pagination">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="page.pageNum"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="page.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				>
				</el-pagination>
			</div>
		</div>
	</div>
</template>

<script>
import authCheck from "@/components/authCheck.vue";
import {
	tacticList,
	addTactic,
	deleteTactic,
	editTactic,
	bmsSeasonList,
} from "@/api/modules/control";
import { getDicts } from "@/api/modules/home";
export default {
	components: { authCheck },
	props: { bmsUnitList: [] },
	data() {
		return {
			chargeTypeDict: [
				{
					dictValue: 1,
					dictLabel: "放电",
				},
				{
					dictValue: -1,
					dictLabel: "充电",
				},
			],
			trueFalseDict: [
				{
					dictValue: 1,
					dictLabel: "是",
				},
				{
					dictValue: 0,
					dictLabel: "否",
				},
			],
			bmsSeasonList: [],
			loading: false,
			page: {
				controlManageIndexId: "",
				pageNum: 1,
				pageSize: 10,
			},
			total: 0,
			tableEditId: "",
			oldTableEditCell: null,
			tacticData: [],
			dialogVisible: false,
			titleDialog: "编辑",
			tacticForm: {
				controlManageIndexId: "",
				beginTime: "",
				endTime: "",
				chargeType: "",
				loadCompdegree: "",
				cosMax: "",
				cosMin: "",
				demandPower: "",
				chgnotdemand: "",
				optimalType: "",
				socMin: "",
				socMax: "",
				antibackflow: "",
			},
			editId: "",
			editProp: [
				"beginTime",
				"p",
				"groupCtrl",
				"directionCmd",
				"followLoad",
				"disablePowReverse",
				"socBottom",
				"socTop",
				"cosBottom",
				"cosTop",
				"ratioPCompensate",
				"powerNeed",
				"constantQ",
				// "beginDay",
				// "endDay",
				"limitMaxPowCh",
				"adjustCosOrQ",
				"ratioQCompensate",
			],
			// 保存进入编辑的cell
			editCells: new Map(),
		};
	},
	watch: {},
	computed: {
		authorize() {
			if (
				this.$route.name !== "lunbo" &&
				this.$store.state.userInfo.authorize == 1
			) {
				return 1;
			} else {
				return 0;
			}
		},
	},
	created() {
		this.getDicts();
	},
	mounted() {},
	methods: {
		number100(v) {
			if (v < 0 || v > 100) {
				this.$message.error("请输入0-100");
			}
		},
		number1(v) {
			if (v < 0 || v > 1) {
				this.$message.error("请输入0-1");
			}
		},
		async getDicts() {
			//充放指令
			// this.chargeTypeDict = await getDicts('charge_type').then((res) => {
			// 	return res.data
			// })
			this.onFocus("created");
		},

		groupCtrlFormat(row) {
			let item = this.bmsUnitList.find((item) => row == item.ctrlGroupId);
			return item ? item.name : "";
		},
		chargeTypeFormat(row) {
			let item = this.chargeTypeDict.find((item) => row == item.dictValue);
			return item ? item.dictLabel : "";
		},
		trueFalseFormat(row) {
			let item = this.trueFalseDict.find((item) => row === item.dictValue);
			return item ? item.dictLabel : "";
		},

		onFocus(type) {
			bmsSeasonList({ pageNum: 1, pageSize: 9999 }).then((res) => {
				this.bmsSeasonList = res.data;
				if (type === "created") {
					this.bmsSeasonList.length > 0
						? (this.page.controlManageIndexId = this.bmsSeasonList[0].id)
						: "";
					this.getData(this.page);
				}
			});
		},
		onChange() {
			this.page.pageNum = 1;
			this.getData(this.page);
		},
		//修改每页条数
		handleSizeChange(val) {
			this.page.pageNum = 1;
			this.page.pageSize = val;
			this.getData(this.page);
		},
		// 翻页
		handleCurrentChange(val) {
			this.page.pageNum = val;
			this.getData(this.page);
		},
		getData(page) {
			this.loading = true;
			tacticList(page).then((res) => {
				this.tacticData = res.rows;
				this.total = res.total;
				this.loading = false;
			});
		},

		onTimeAdd() {
			let obj = {
				beginTime: "",
				p: "",
				groupCtrl: "",
				directionCmd: "",
				followLoad: "",
				disablePowReverse: "",
				socBottom: "",
				socTop: "",
				cosBottom: "",
				cosTop: "",
				ratioPCompensate: "",
				powerNeed: "",
				constantQ: "",
				adjustCosOrQ: "",
				// beginDay: "",
				// endDay: "",
				limitMaxPowCh: "",
				ratioQCompensate: "",
			};
			this.tacticData.unshift(obj);
		},
		handleSeasonEdit(row) {
			this.tacticForm = {
				controlManageIndexId: row.controlManageIndexId,
				beginTime: row.beginTime,
				endTime: row.endTime,
				chargeType: String(row.chargeType),
				loadCompdegree: row.loadCompdegree,
				cosMax: row.cosMax,
				cosMin: row.cosMin,
				demandPower: row.demandPower,
				chgnotdemand: String(row.chgnotdemand),
				optimalType: String(row.optimalType),
				socMin: row.socMin,
				socMax: row.socMax,
				antibackflow: String(row.antibackflow),
			};
			this.editId = row.id;
			this.titleDialog = "编辑";
			this.dialogVisible = true;
		},
		/** 鼠标移入cell */
		handleCellEnter(row, column, cell, event) {
			if (this.authorize) {
				const property = column.property;
				if (this.editProp.includes(property)) {
					cell
						.querySelector(".editable-cell__val")
						.classList.add("editable-cell__val--hover");
				}
			}
		},
		/** 鼠标移出cell */
		handleCellLeave(row, column, cell, event) {
			const property = column.property;
			if (this.editProp.includes(property)) {
				cell
					.querySelector(".editable-cell__val")
					.classList.remove("editable-cell__val--hover");
			}
		},
		/** 点击cell */
		handleCellClick(row, column, cell, event) {
			if (this.authorize && column.label !== "操作") {
				// if (row.id === this.tableEditId || this.tableEditId == "") {
				// 	column.label !== "操作"
				// 		? (this.tableEditId = row.id)
				// 		: (this.tableEditId = "");

				// const button = this.$refs.ElTableRef.$el.querySelector(
				// 	".el-button.el-button--primary"
				// );
				// console.log(this.$refs.ElTableRef.$el);
				// console.log(button);
				const saveBtns =
					this.$refs.ElTableRef.$el.querySelectorAll(".save-btn");
				if (saveBtns.length > 0 && row.id !== this.tableEditId) {
					this.$message.error("请先保存数据");
					return;
				}
				if (this.oldTableEditCell !== cell && this.oldTableEditCell !== null) {
					this.cancelEditable(this.oldTableEditCell);
				}
				this.oldTableEditCell = cell;
				this.tableEditId = row.id;
				const property = column.property;
				if (this.editProp.includes(property)) {
					// 保存cell
					this.saveCellClick(row, cell);
					cell.querySelector(".editable-cell__val").style.display = "none";
					cell.querySelector(".editable-cell__input").style.display = "block";
					cell.querySelector("input").focus();
				}

				// } else {
				// 	this.$message({
				// 		type: "warnning",
				// 		message: "请先保存数据!",
				// 	});
				// }
			}
		},
		/** 取消编辑状态 */
		cancelEditable(cell) {
			cell.querySelector(".editable-cell__val").style.display = "block";
			cell.querySelector(".editable-cell__input").style.display = "none";
		},
		/** 保存进入编辑的cell */
		saveCellClick(row, cell) {
			if (this.editCells.has(row)) {
				this.editCells.get(row).add(cell);
			} else {
				this.editCells.set(row, new Set([cell]));
			}
			this.updateRowSave(row);
		},
		updateRowSave(row) {
			// this.tacticData.map((item) => {
			// 	if (item.id == row.id) {
			// 		this.$set(item, "isEdit", this.editCells.has(row));
			// 	}
			// });
			row.isEdit = this.editCells.has(row);
		},

		save(row) {
			if (row.socBottom < 0 || row.socBottom > 100) {
				this.$message.error("SOC下限请输入0-100的值");
				return;
			}
			if (row.socTop < 0 || row.socTop > 100) {
				this.$message.error("SOC上限请输入0-100的值");
				return;
			}
			if (row.cosBottom < 0 || row.cosBottom > 1) {
				this.$message.error("COS下限请输入0-1的值");
				return;
			}
			if (row.cosTop < 0 || row.cosTop > 1) {
				this.$message.error("COS上限请输入0-1的值");
				return;
			}
			if (row.ratioPCompensate < 0 || row.ratioPCompensate > 1) {
				this.$message.error("有功负荷补偿度请输入0-1的值");
				return;
			}
			if (row.ratioQCompensate < 0 || row.ratioQCompensate > 1) {
				this.$message.error("无功补偿度请输入0-1的值");
				return;
			}
			delete row.isEdit;
			if (row.id) {
				//编辑
				editTactic(row).then(() => {
					this.getData(this.page);
					this.$message({
						type: "success",
						message: "修改成功!",
					});
				});
				this.saveSuccess(row);
			} else {
				row.controlManageIndexId = this.page.controlManageIndexId;
				addTactic(row).then(() => {
					this.page.pageNum = 1;
					this.getData(this.page);
					this.$message({
						type: "success",
						message: "新增成功!",
					});
					this.saveSuccess(row);
				});
			}
		},
		saveSuccess(row) {
			this.tableEditId = "";
			this.oldTableEditCell = null;
			this.editCells.get(row).forEach((cell) => {
				this.cancelEditable(cell);
			});
			this.editCells.delete(row);
			this.updateRowSave(row);
		},
		handleSeasonDelete(row) {
			this.$confirm("确定删除此数据吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(() => {
					if (row.id) {
						deleteTactic({
							id: row.id,
							controlManageIndexId: row.controlManageIndexId,
						}).then((res) => {
							this.getData(this.page);
							this.$message({
								type: "success",
								message: "删除成功!",
							});
						});
					} else {
						this.tacticData.shift();
						this.getData(this.page);
						this.cancelAllEdit();
					}
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除",
					});
				});
		},
		cancelAllEdit() {
			const inputs = this.$refs.ElTableRef.$el.querySelectorAll(
				".editable-cell__input"
			);
			inputs.forEach((input) => {
				input.style.display = "none";
			});
			const vals = this.$refs.ElTableRef.$el.querySelectorAll(
				".editable-cell__val"
			);
			vals.forEach((val) => {
				val.style.display = "block";
			});
		},
	},
};
</script>
<style lang="scss" scoped>
.titles {
	display: flex;
	justify-content: space-between;
	.el-button--primary {
		background-color: #045eed;
		border-color: #045eed;
		height: 36px;
		margin: 10px 10px 0 0;
	}
	.el-button {
		height: 36px;
		margin: 9px 22px 0 0;
	}
}
.table-main {
	height: 100%;
	.table-container {
		padding: 10px 22px;
		height: calc(100% - 56px);
	}
	.el-pagination {
		padding: 10px 5px 2px;
	}
	.editable-cell__input {
		display: none;
		.el-input__inner {
			padding: 0 8px;
			font-size: 12px;
		}
	}

	.editable-cell__val {
		box-sizing: border-box;
		height: 32px;
		line-height: 32px;
		border: 1px solid transparent;

		&--hover {
			border-color: #dddddd;
			border-radius: 4px;
			cursor: text;
		}
	}
}
</style>
